/**
 * Driver.java created by 漫时光。 at 下午1:19:40 2017年7月21日
 */
package compiler.antlr.javag4;

import java.io.IOException;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;

import compiler.antlr.javag4.JavaParser.CompilationUnitContext;
import core.LoggerSupport;

/**
 * @author 漫时光。<br>
 */
class ClassDec extends LoggerSupport implements ParseTreeVisitor<String>{

	/**
	 * 
	 */
	String [] rules;
	public ClassDec(String []rules) {
		this.rules = rules;
	}
	@Override
	public String visit(ParseTree tree) {
		System.out.println("tree");
		return null;
	}
	@Override
	public String visitChildren(RuleNode node) {
		if(node instanceof CompilationUnitContext){
			handle(node,0);
			return "";
		}
		
		return null;
	}
	void print(ParserRuleContext prc,int level){
		String ruleName  =  rules[prc.getRuleIndex()];
		logger.info("level: {} ruleName-->{}",level,ruleName);
	}
	void print(TerminalNodeImpl tn,int level){
		String name = tn.getSymbol().getText();
		logger.info("level: {} TER-->{}",level,name);
	}
	
	void handle(ParseTree pt,int level){
		if(pt instanceof ParserRuleContext){
			ParserRuleContext prc = (ParserRuleContext)pt;
			print(prc,level);
			
		}else if(pt instanceof TerminalNodeImpl){
			print((TerminalNodeImpl)pt,level);
		}
		int count = pt.getChildCount();
		for(int i =0;i<count;i++){
			ParseTree tree = pt.getChild(i);
			handle(tree,level+1);
		}
	}
	
	

	@Override
	public String visitTerminal(TerminalNode node) {
		return null;
	}

	@Override
	public String visitErrorNode(ErrorNode node) {
		return null;
	}
	
}
public class Bootstrap {
	public static void main(String[] args) throws IOException {
		CharStream cs = new ANTLRInputStream(Bootstrap.class.getResourceAsStream("javasrc.txt"));
		JavaParser jp = new JavaParser(new CommonTokenStream(new JavaLexer(cs)));
		String rules[] = jp.getRuleNames();
		ParserRuleContext rule = jp.compilationUnit();
//		rule.accept(new Exec());
		rule.accept(new ClassDec(rules));
//		System.out.println(rule.accept(new Exec()));
	}
}
